package com.haust.leyou.controller;

import com.haust.leyou.config.JwtProperties;
import com.haust.leyou.pojo.UserInfo;
import com.haust.leyou.service.AuthService;
import com.haust.leyou.utils.CookieUtils;
import com.haust.leyou.utils.JwtUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Auther: csp1999
 * @Date: 2020/12/20/13:29
 * @Description:
 */
@Controller
//@EnableConfigurationProperties(JwtProperties.class)
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 用于用户登录：
     * 根据用户名和密码进行身份认证，并获取token存入 cookie
     *
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/accredit")
    public ResponseEntity<Void> accredit(@RequestParam("username") String username,
                                         @RequestParam("password") String password,
                                         HttpServletRequest request,
                                         HttpServletResponse response) {

        // 根据用户名密码获取token  ---> 先判断user是否存在
        String token = authService.accredit(username, password);

        if (StringUtils.isBlank(token)) {
            // 401：身份认证未通过
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }

        // 将token 设置到 cookie
        CookieUtils.setCookie(
                request,
                response,
                jwtProperties.getCookieName(),
                token,
                jwtProperties.getExpire() * 60);

        return ResponseEntity.status(HttpStatus.OK).build();
    }

    /**
     * 从cookie中取出token 并解析得到userInfo
     *
     * @param token
     * @return
     */
    @GetMapping("/verify")
    public ResponseEntity<UserInfo> verify(@CookieValue("LEYOU_TOKEN") String token,
                                           HttpServletRequest request,
                                           HttpServletResponse response) {

        try {
            // 通过jwt 工具类使用公钥解析jwt
            // 获取token中的用户信息
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
            System.out.println(userInfo);

            if (userInfo == null) {
                // 401
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
            }

            // 刷新jwt 中有效时间 =>30分钟
            token = JwtUtils.generateToken(
                    userInfo,
                    jwtProperties.getPrivateKey(),
                    jwtProperties.getExpire());

            // 刷新cookie 中的有效时间
            CookieUtils.setCookie(
                    request, response,
                    jwtProperties.getCookieName(),
                    token,
                    jwtProperties.getExpire() * 60);

            return ResponseEntity.ok(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 401
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
    }
}
